var markDownVue = new Vue({
	el: "#vue",
	data: {
		showSavedMarkdownList: false,
		markDownTips: "",
		changeNum:0,
		mySavedMarkDownListKey: [],
		curMarkDown: {title:"MarkDown示例",createTime:"",finalTime:"",data:""}
	},
	created(){
		if(window.localStorage.getItem("mySavedMarkDownListKey")==null){
			window.localStorage.setItem("mySavedMarkDownListKey","");
		}
		this.mySavedMarkDownListKey = window.localStorage.getItem("mySavedMarkDownListKey").split(",");
		if(this.mySavedMarkDownListKey[0] == ""){
			this.mySavedMarkDownListKey.pop();
		}
		this.mySavedMarkDownListKey.reverse();
	},
	mounted(){
		this.curMarkDown["createTime"] = this.dateFormat(1*new Date);
		this.ajaxFile("./example.md", function(res){ 
			window.markDownVue.curMarkDown["data"] =res;
		});
	},
	methods:{
		//自动保存
		listenChange: function() {
			this.changeNum++;
			if(this.changeNum == 20){
				this.saveMarkDown();
				this.markDownTips = `自动保存时间: ${this.curMarkDown["finalTime"]}`;
				this.changeNum = 0;
			}
		},
		//新建MarkDown
		newMarkDown:function(){
			let res = confirm("新建文档将会清空当前内容，是否继续？");
			if(!res){return;}
			this.curMarkDown["title"] = "在此输入标题";
			this.curMarkDown["createTime"] = this.dateFormat(1*new Date);
			this.curMarkDown["data"] = "";
			this.markDownTips = "";
			window.markDown.setMarkdown(this.curMarkDown["data"]);
		},
		//保存MarkDown到浏览器
		saveMarkDown:function(){
			if(this.curMarkDown["createTime"] == ""){
				this.curMarkDown["createTime"] = this.dateFormat(1*new Date);
			}
			if(!this.mySavedMarkDownListKey.includes(this.curMarkDown["createTime"])){
				this.mySavedMarkDownListKey.unshift(this.curMarkDown["createTime"]);
			}
			let tempKey = [].concat(this.mySavedMarkDownListKey);
			window.localStorage.setItem("mySavedMarkDownListKey",tempKey.reverse().toString());
			this.curMarkDown["data"] = window.markDown.getMarkdown();
			this.curMarkDown['finalTime'] = this.dateFormat(1*new Date);
			this.changeNum = 0;
			this.markDownTips = `手动保存时间: ${this.curMarkDown["finalTime"]}`;
			this.isSave=true;
			window.localStorage.setItem(this.curMarkDown["createTime"],JSON.stringify(this.curMarkDown));
		},
		//单文件导入
		importMarkDown:function(){
			let res = confirm("打开文档将会清空当前内容，是否继续？");
			if(!res){return;}
			let input = document.querySelector("#file");
			input.addEventListener("change", function(ev) {
				let event = ev || window.event;
				let files = this.files;
				let file = files[0];
				let reader = new FileReader();
				reader.onload = (function(file) {
					return function(e) {
						window.markDownVue.curMarkDown["data"] = this.result;
						window.markDown.setMarkdown(window.markDownVue.curMarkDown["data"]);
					};
				})();
				//读取文件内容
				reader.readAsText(file,"utf-8");
				window.markDownVue.curMarkDown["title"] = this.files[0].name.replace(/\..*/,"");
				window.markDownVue.curMarkDown["createTime"] = window.markDownVue.dateFormat(1*new Date);
			}, false);
			input.click();
			this.markDownTips = "";
		},
		//单文件导出或批量导出
		exportMarkDown:function(key){
			if(key == "all"){
				let zip = new JSZip();
				zip.file("MarkDown编辑器导出.txt", "导出的文件是md\n");
				for(let i = 0, j = window.localStorage.length; i < j; i++){
					let key = window.localStorage.key(i);
					if(key != "mySavedMarkDownListKey"){
						let value = JSON.parse(window.localStorage.getItem(key));
						let md = zip.folder("MarkDown");
						md.file(value["title"].replace(/\//g,"_")+".md", value["data"]);
					}
				}
				zip.generateAsync({type:"blob"}).then(function(content) {
					// see FileSaver.js
					saveAs(content, "MarkDown导出.zip");
				});
			}else{
				//单文件导出相关函数
				(function(name, data) {
					var urlObject = window.URL || window.webkitURL || window;
					var export_blob = new Blob([data]);
					var save_link = document.createElementNS("http://www.w3.org/1999/xhtml", "a")
					save_link.href = urlObject.createObjectURL(export_blob);
					save_link.download = name;
					(function(obj) {
						var ev = document.createEvent("MouseEvents");
						ev.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
						obj.dispatchEvent(ev);
					})(save_link);
				})(this.curMarkDown["title"]+".md",this.curMarkDown["data"]);
			}
		},
		//显示隐藏文件列表
		myMarkDownList:function(){
			this.showSavedMarkdownList = !this.showSavedMarkdownList;
		},
		//编辑选中的MarkDown
		editMakrdown:function(key){
			let markDownObj = JSON.parse(window.localStorage.getItem(key));
			this.curMarkDown['createTime'] = key;
			this.curMarkDown['title'] = markDownObj["title"];
			this.curMarkDown['data'] = markDownObj["data"];
			window.markDown.setMarkdown(this.curMarkDown['data']);
			//this.showSavedMarkdownList = !this.showSavedMarkdownList;
		},
		//删除选中的MarkDown
		deleteMakrdown:function(key){
			let res = confirm("删除："+this.getMarkDown(key)["title"]);
			if(res){
				this.mySavedMarkDownListKey.splice(this.mySavedMarkDownListKey.indexOf(key),1);
				window.localStorage.removeItem(key);
				window.localStorage.setItem("mySavedMarkDownListKey",this.mySavedMarkDownListKey.toString())
			}
		},
		//根据创建日期返回对应的MarkDown
		getMarkDown(key){
			return JSON.parse(window.localStorage.getItem(key));
		},
		// 通过ajax请求文件
		ajaxFile:function(file, callback) {
			let ajax = new XMLHttpRequest();
			ajax.overrideMimeType("application/json");
			ajax.open("GET", file, true);
			ajax.onreadystatechange = function() {
				if (ajax.readyState === 4 && ajax.status == "200") {
					callback(ajax.responseText);
				}
			}
			ajax.send(null);
		},
		//时间格式化
		dateFormat: function(t) {
			let e = "yyyy-MM-dd HH:mm:ss",
				a = function(t, e) {
					let a = "",
						i = t < 0,
						o = String(Math.abs(t));
					return o.length < e && (a = new Array(e - o.length + 1).join("0")), (i ? "-" : "") + a + o
				},
				i = function(t, a) {
					e = e.replace(t, a)
				},
				o = (t = new Date(t)).getFullYear(),
				n = t.getMonth() + 1,
				s = t.getDate(),
				r = t.getHours(),
				d = t.getMinutes(),
				u = t.getSeconds(),
				l = t.getMilliseconds();
			return i(/yyyy/g, a(o, 4)), i(/yy/g, a(parseInt(o.toString().slice(2), 10), 2)), i(/MM/g, a(n, 2)), i(/M/g, n), i(
				/dd/g, a(s, 2)), i(/d/g, s), i(/HH/g, a(r, 2)), i(/H/g, r), i(/hh/g, a(r % 12, 2)), i(/h/g, r % 12), i(/mm/g, a(
				d, 2)), i(/m/g, d), i(/ss/g, a(u, 2)), i(/s/g, u), i(/SSS/g, a(l, 3)), i(/S/g, l), e
		},
	}
});


//实现拖拽文件
const drag = document.querySelector("#editormd");
drag.addEventListener("dragenter", function (e) {
  e.preventDefault();
  e.stopPropagation();
}, false);
 
drag.addEventListener("dragover", function (e) {
  e.preventDefault();
  e.stopPropagation();
}, false);
 
drag.addEventListener("dragleave", function (e) {
  e.preventDefault();
  e.stopPropagation();
}, false);
drag.addEventListener("drop", function (e) {
	e.preventDefault();
	e.stopPropagation();
	var df = e.dataTransfer;
	// 用webkitGetAsEntry禁止上传目录
	if(df.items[0].kind === "file" && df.items[0].webkitGetAsEntry().isFile) {
		let file = df.items[0].getAsFile();
		let reader = new FileReader();
		reader.onload = (function(file) {
			return function(e) {
				window.markDownVue.curMarkDown["data"] = this.result;
				window.markDown.setMarkdown(window.markDownVue.curMarkDown["data"]);
			};
		})();
		window.markDownVue.curMarkDown["title"] = df.items[0].getAsFile().name.replace(/\..*/,"");
		window.markDownVue.curMarkDown["createTime"] = window.markDownVue.dateFormat(1*new Date);
		//读取文件内容
		reader.readAsText(df.items[0].getAsFile(),"utf-8");
	}
}, false);